package com.itheima.service.impl;

import com.itheima.entity.HotSetMealVO;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.ReportService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description 统计服务接口实现类
 * @Author makun
 * @Date 2023/9/20 16:46
 * @Version 1.0
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public Map<String, List<Integer>> getMemberReport() {
        ArrayList<Integer> months = new ArrayList<>();
        ArrayList<Integer> memberCount = new ArrayList<>();
        // 获取当前月
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        // 循环查出每月会员
        for (int i = 1; i <= month; i++) {
            months.add(i);
            memberCount.add(memberMapper.selectCountByMonthOfCurrentYear(i));
        }
        // 将数据装入map集合中
        HashMap<String, List<Integer>> result = new HashMap<>();
        result.put("months", months);
        result.put("memberCount", memberCount);

        return result;
    }

    @Override
    public Map<String, List<?>> getSetMealReport() {
        ArrayList<String> setmealNames = new ArrayList<>();
        ArrayList<ECharsPieDate> setmealCount = new ArrayList<>();
        // 查询所有的套餐
        List<Setmeal> setmeals = setMealMapper.selectList(null);
        // 遍历所有套餐并装载数据
        for (Setmeal setmeal : setmeals) {
            setmealNames.add(setmeal.getName());
            setmealCount.add(new ECharsPieDate(setmeal.getName(), orderMapper.selectCountBySetMealId(setmeal.getId())));
        }
        // 将数据装载到返回对象中
        HashMap<String, List<?>> result = new HashMap<>();
        result.put("setmealNames", setmealNames);
        result.put("setmealCount", setmealCount);

        return result;
    }

    @Override
    public Map<String, Object> getBusinessReportData() {

        HashMap<String, Object> result = new HashMap<>();
        result.put("reportDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        result.put("todayNewMember", memberMapper.selectTodayNewMember());
        result.put("totalMember", memberMapper.selectTotalMember());
        result.put("thisWeekNewMember", memberMapper.selectThisWeekNewMember());
        result.put("thisMonthNewMember", memberMapper.selectThisMonthNewMember());
        result.put("todayOrderNumber", orderMapper.selectTodayOrderNumber());
        result.put("todayVisitsNumber", orderMapper.selectTodayVisitsNumber());
        result.put("thisWeekOrderNumber", orderMapper.selectThisWeekOrderNumber());
        result.put("thisWeekVisitsNumber", orderMapper.selectThisWeekVisitsNumber());
        result.put("thisMonthOrderNumber", orderMapper.selectThisMonthOrderNumber());
        result.put("thisMonthVisitsNumber", orderMapper.selectThisMonthVisitsNumber());
        result.put("hotSetmeal", setMealMapper.selectHotSetMealRank(4));

        return result;
    }

    @Override
    public boolean exportBusinessReport(HttpServletResponse response) {
        try {
            Map<String, Object> result = getBusinessReportData();
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<HotSetMealVO> hotSetmeal = (List<HotSetMealVO>) result.get("hotSetmeal");

            // 使用ClassLoader获取根路径
            InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("static/template/report_template.xlsx");

            assert resourceAsStream != null;
            XSSFWorkbook excel =new XSSFWorkbook(resourceAsStream);
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate); // 设置时间
            // 设置今日新会员数与总会员数
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            // 设置本周新会员数与本月新会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);
            // 设置今日预约数与今日就诊数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);
            // 设置本周预约数与本周就诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            // 设置本月预约数与本月就诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);
            // 设置最热门套餐
            int rowNumber = 12;
            for (HotSetMealVO hotSetMealVO : hotSetmeal) {
                String name = hotSetMealVO.getName();
                Integer setMealCount = hotSetMealVO.getSetMealCount();
                Float proportion = hotSetMealVO.getProportion();
                String remark = hotSetMealVO.getRemark();
                row = sheet.getRow(rowNumber);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setMealCount);
                row.getCell(6).setCellValue(proportion);
                row.getCell(7).setCellValue(remark);
                rowNumber++;
            }
            // 通过输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            excel.write(outputStream);
            outputStream.close();
            excel.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 用于装载饼状图图标数据
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class ECharsPieDate {
        private String name;
        private Integer value;
    }
}
